import nodemailer from 'nodemailer'
import yaml from 'js-yaml'
import http from 'node:http'
import fs from 'node:fs'
import url from 'node:url'

const mailInfo = yaml.load(fs.readFileSync('./mail.yaml', 'utf8'))
console.log('mailInfo', mailInfo);
// 初始化邮件服务
const transport = nodemailer.createTransport({
  service: 'qq', // 服务商
  host: 'smtp.qq.com',
  post: 587,
  secure: true,
  auth: {
    user: mailInfo.user, // 发送者的邮箱账号
    pass: mailInfo.pass, // 密码或者是授权码
  }
})

http.createServer(async (request, response) => {
  const { pathname } = url.parse(request.url)
  const { method } = request

  if (method === 'POST' && pathname === '/send/mail') {
    let data = '';
    request.on('data', (chunk) => {
      data += chunk.toString()
    })
    request.on('end', () => {
      const { to, subject, text } = JSON.parse(data)
      
      transport.sendMail({
        to, // 收件人
        from: mailInfo.user, // 发件人
        subject, // 主题
        text, // 邮件内容
      })
      response.end()
    })
  }
}).listen(3000, () => {
  console.log('监听3000端口了');
})



